package edu.cuc.chap02.demo02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by bingruiqi on 2017/9/11.
 */
public class TimeServer {
	public void bind(int port) throws InterruptedException {
		EventLoopGroup bossgroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossgroup, workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			ChannelFuture future = b.bind(port);
			future.channel().closeFuture().sync();
		} finally {
			bossgroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}

	}

	private class ChildChannelHandler extends ChannelInitializer {
		@Override
		protected void initChannel(Channel channel) throws Exception {
			channel.pipeline().addLast(new TimeServerHandler());
		}
	}

	public static void main(String[] args) throws InterruptedException {
		int port = 9898;
		if (args.length > 0 && args != null) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception ex) {

			}
		}
		new TimeServer().bind(port);
	}
}
